package com.ybkj.daijia.api.apirest;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.RandomString;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.mapper.SmsSendBlackRecordMapper;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.PhoneSmsRecord;
import com.ybkj.daijia.server.model.SmsSendBlackRecord;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.PhoneSmsRecordService;
import com.ybkj.daijia.server.service.SmsService;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("ApiSmsProcessController")
@RequestMapping(value = "api/sms/")
public class SmsProcessController {

    private static final Logger logger = LoggerFactory.getLogger(SmsProcessController.class);

    @Autowired
    private CompanyService companyService;

    @Autowired
    private PhoneSmsRecordService phoneSmsRecordService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private SmsSendBlackRecordMapper blackRecordMapper;

    @Autowired
    private SmsService smsService;

    /**
     * 短信验证码
     *
     * @param phone
     * @return
     */

    @RequestMapping(value = "send")
    public @ResponseBody
    Result<String> sendVcode(String phone) {
        Company mainCompany = companyService.getMain();

        Result<String> result = new Result();

        PhoneSmsRecord phoneSmsRecord = phoneSmsRecordService.findByPhone(phone);

        if (phoneSmsRecord != null) {
            logger.info("短信验证码记录  {phone:" + phoneSmsRecord.getPhone() + ",vcode:" + phoneSmsRecord
                .getVcode() + ",expired:" + phoneSmsRecord.getExpired() + "}");
            long time = (System.currentTimeMillis() - phoneSmsRecord.getExpired().getTime()) / 1000; //多少秒

            if (time < 120) {//2分内禁止发送
                result.setErrorcode("0");
                result.setObject(time);
                logger.info("两分钟内禁止发送短信");
                return result;
            }

            if (time >= 120 && time < 30 * 60) {//30分内发送旧的
                result.setSuccess(true);
                phoneSmsRecord.setExpired(new Date());
                phoneSmsRecord.setPhone(phone);
                phoneSmsRecordService.update(phoneSmsRecord);

                result.setResult(phoneSmsRecord.getVcode());

                try {
//					String con="尊敬的用户您好,验证码："+phoneSmsRecord.getVcode();

                    SmsTemplet templet = smsService
                        .findByAlias(mainCompany.getId(), SmsType.customDriver);
//					if(templet==null){
//						SmsTemplet smsTemplet=new SmsTemplet();
//						smsTemplet.setSmsType(SmsType.custom);
//						smsTemplet.setCompanyId(mainCompany.getId());
//						smsTemplet.setContent("{content}");
//						smsService.insertSmsTemplate("自定义短信",SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//					}
                    if (templet != null && StringUtils.isNotBlank(templet.getContent())) {
                        //smsService.sendSms(phone, "custom", "{\"content\":\""+con+"\"}",mainCompany.getId(),2,mainCompany.getSignName());
                        //短信发送（改）
                        JSONObject smsParam = new JSONObject();
                        smsParam.put("code", phoneSmsRecord.getVcode());
                        smsService.sendSms(phone, templet.getTemplateId(), smsParam.toJSONString(),
                            mainCompany.getId(), 2, mainCompany.getSignName());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                return result;
            } else {//超过30分 发送新的
                result.setErrorcode("1");
                result.setSuccess(true);
                String newCode = String.valueOf(RandomString.randomNum(4));
                phoneSmsRecord.setExpired(new Date());
                phoneSmsRecord.setVcode(newCode);
                phoneSmsRecord.setPhone(phone);
                phoneSmsRecordService.update(phoneSmsRecord);

                result.setResult(newCode);

                try {
                    String con = "尊敬的用户您好,验证码：" + newCode;
                    SmsTemplet templet = smsService
                        .findByAlias(mainCompany.getId(), SmsType.customDriver);
//					if(templet==null){
//						SmsTemplet smsTemplet=new SmsTemplet();
//						smsTemplet.setSmsType(SmsType.custom);
//						smsTemplet.setCompanyId(mainCompany.getId());
//						smsTemplet.setContent("{content}");
//						smsService.insertSmsTemplate("自定义短信",SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//					}
                    if (templet != null && StringUtils.isNotBlank(templet.getContent())) {
                        //smsService.sendSms(phone, "custom", "{\"content\":\""+con+"\"}",mainCompany.getId(),2,mainCompany.getSignName());
                        //短信发送（改）
                        JSONObject smsParam = new JSONObject();
                        smsParam.put("code", newCode);
                        smsService.sendSms(phone, templet.getTemplateId(), smsParam.toJSONString(),
                            mainCompany.getId(), 2, mainCompany.getSignName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
            }
        } else {
            String newCode = String.valueOf(RandomString.randomNum(4));
            phoneSmsRecord = new PhoneSmsRecord();
            phoneSmsRecord.setExpired(new Date());
            phoneSmsRecord.setPhone(phone);
            phoneSmsRecord.setVcode(newCode);
            phoneSmsRecordService.save(phoneSmsRecord);
            logger.info(
                "生成一条新短信验证码记录  {phone:" + phoneSmsRecord.getPhone() + ",vcode:" + phoneSmsRecord
                    .getVcode() + ",expired:" + phoneSmsRecord.getExpired() + "}");

            result.setResult(newCode);

            try {
                String con = "尊敬的用户您好,验证码：" + newCode;
                SmsTemplet templet = smsService
                    .findByAlias(mainCompany.getId(), SmsType.customDriver);
//				if(templet==null){
//					SmsTemplet smsTemplet=new SmsTemplet();
//					smsTemplet.setSmsType(SmsType.custom);
//					smsTemplet.setCompanyId(mainCompany.getId());
//					smsTemplet.setContent("{content}");
//					smsService.insertSmsTemplate("自定义短信",SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//				}
                if (templet != null && StringUtils.isNotBlank(templet.getContent())) {
                    //smsService.sendSms(phone, "custom", "{\"content\":\""+con+"\"}",mainCompany.getId(),2,mainCompany.getSignName());
                    //短信发送（改）
                    JSONObject smsParam = new JSONObject();
                    smsParam.put("code", newCode);
                    smsService.sendSms(phone, templet.getTemplateId(), smsParam.toJSONString(),
                        mainCompany.getId(), 2, mainCompany.getSignName());
                    logger.info("发送验证码成功");
                }

                result.setSuccess(true);
            } catch (Exception e) {
            }

            return result;
        }

    }

    /**************************************************************************************************
     *
     * 微信V5升级使用的短信验证在这里，为了不与其他版本冲突，这里再COPY一份
     *
     **************************************************************************************************/

    /**
     * 短信验证码
     *
     * @param request
     * @param IP
     * @param phone
     * @param imageCode
     * @return 返回错误码说明:<br> 0 ==> 发送成功<br> -1 ==> 系统异常<br> -2 ==> 参数错误<br> -3 ==> 图片验证码验证失败<br> -4
     * ==> 验证码获取大于3，前台加载图片验证码，或没有传入图片验证码<br> -5 ==> 120秒内禁止发送<br>
     */
    @ResponseBody
    @RequestMapping("sendup")
    public Result<String> sendVcodeUseImageCode(HttpServletRequest request, String IP, String phone,
        String imageCode) {
        Result<String> result = new Result(); // 返回对象
        try {
            // 验证参数
            if (null == IP
                || IP.isEmpty()
                || null == phone
                || phone.isEmpty()) {
                result.setSuccess(false);
                result.setMessage("参数错误");
                result.setErrorcode("-2");
                return result;
            }

            // 验证IP，手机号，同一个IP,3次重复输入一个手机号点击获取验验证码，则需要先经过图片验证才能再继续获取验证码
            int isDanger = smsService.isDangerForSendVCode(IP, phone, imageCode);
            switch (isDanger) {
                case 0: // 图片验证码验证失败
                    result.setSuccess(false);
                    result.setMessage("图片验证码验证失败");
                    result.setErrorcode("-3");
                    return result;

                case 1: // 没有风险，正常发送验证码

                    break;

                case 2: // 通知前台加载图片验证码，或请输入验证码
                    result.setSuccess(false);
                    result.setMessage("验证码获取大于3，前台加载图片验证码，或者没有传入验证码");
                    result.setErrorcode("-4");
                    return result;

                default:
                    break;
            }

            // 获取主公司
            Company mainCompany = companyService.getMain();
            Long companyId = mainCompany.getId();
            String companyAbbreviation = mainCompany.getAbbreviation();
            String companySignName = mainCompany.getSignName();

            // 获取该电话的电话短信记录，如果没有记录，则马上发送验证码；如果已经发送过验证码，则判断发送间隔时长
            PhoneSmsRecord phoneSmsRecord = phoneSmsRecordService.findByPhone(phone);

            // 没有记录，马上发送验证码
            if (phoneSmsRecord == null) {
                String newCode = String.valueOf(RandomString.randomNum(4));
                phoneSmsRecord = new PhoneSmsRecord();
                phoneSmsRecord.setExpired(new Date());
                phoneSmsRecord.setPhone(phone);
                phoneSmsRecord.setVcode(newCode);
                phoneSmsRecord.setCompanyId(companyId);
                phoneSmsRecordService.save(phoneSmsRecord);
                smsService.sendSmsMsg(IP, phone, newCode, companyId, companyAbbreviation,
                    companySignName); // 发送验证码

                // 返回数据
                result.setSuccess(true);
                result.setMessage("ok");
                result.setErrorcode("0");
                return result;
            }

            // 已经发送过验证码，判断发送间隔时长
            long time =
                (System.currentTimeMillis() - phoneSmsRecord.getExpired().getTime()) / 1000; // 获取已经发送了多上秒

            // 120秒内禁止发送
            if (time < 120) {
                result.setSuccess(false);
                result.setErrorcode("-5");
                result.setMessage("120秒内禁止发送");
                result.setLongValue(120 - time);
                return result;
            }

            // 120秒~1800秒发送旧的验证码
            if (time >= 120 && time < 30 * 60) {
                phoneSmsRecord.setExpired(new Date());
                phoneSmsRecord.setPhone(phone);
                phoneSmsRecordService.update(phoneSmsRecord);
                smsService.sendSmsMsg(IP, phone, phoneSmsRecord.getVcode(), companyId,
                    companyAbbreviation, companySignName);
            }

            // 超过1800秒发送新的验证码
            if (time >= 30 * 60) {
                String newCode = String.valueOf(RandomString.randomNum(4));
                phoneSmsRecord.setExpired(new Date());
                phoneSmsRecord.setVcode(newCode);
                phoneSmsRecord.setPhone(phone);
                phoneSmsRecordService.update(phoneSmsRecord);
                smsService.sendSmsMsg(IP, phone, newCode, companyId, companyAbbreviation,
                    companySignName);
            }

            // 返回数据
            result.setSuccess(true);
            result.setMessage("ok");
            result.setErrorcode("0");
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("系统异常");
            result.setErrorcode("-1");
        }
        return result;
    }

    /**
     * 微信发送验证码v2升级版，必须验证图片验证码才能发送短信
     *
     * @param request
     * @param IP
     * @param phone
     * @param imageCode
     * @return 返回错误码说明:<br> 0 ==> 发送成功<br> -1 ==> 系统异常<br> -2 ==> 参数错误<br> -3 ==> 图片验证码验证失败<br> -4
     * ==> 120秒内禁止发送<br>
     */
    @ResponseBody
    @RequestMapping("sendupv2")
    public Result<String> sendVcodeUseImageCodeV2(HttpServletRequest request, String IP,
        String phone, String imageCode) {
        Result<String> result = new Result<String>(); // 返回对象
        try {
            // 验证参数
            if (null == IP
                || IP.isEmpty()
                || null == phone
                || phone.isEmpty()
                || null == imageCode
                || imageCode.isEmpty()) {
                result.setSuccess(false);
                result.setMessage("参数错误");
                result.setErrorcode("-2");
                return result;
            }

            // 图片验证通过发送验证码，未通过不发送
            boolean isPass = smsService.validateImgCode(IP, phone, imageCode);
            if (!isPass) {
                result.setSuccess(false);
                result.setMessage("图片验证码验证失败");
                result.setErrorcode("-3");
                return result;
            }

            // 获取主公司
            Company mainCompany = companyService.getMain();
            Long companyId = mainCompany.getId();
            String companyAbbreviation = mainCompany.getAbbreviation();
            String companySignName = mainCompany.getSignName();

            // 获取该电话的电话短信记录，如果没有记录，则马上发送验证码；如果已经发送过验证码，则判断发送间隔时长
            PhoneSmsRecord phoneSmsRecord = phoneSmsRecordService.findByPhone(phone);

            // 没有记录，马上发送验证码
            if (phoneSmsRecord == null) {
                String newCode = String.valueOf(RandomString.randomNum(4));
                phoneSmsRecord = new PhoneSmsRecord();
                phoneSmsRecord.setExpired(new Date());
                phoneSmsRecord.setPhone(phone);
                phoneSmsRecord.setVcode(newCode);
                phoneSmsRecord.setCompanyId(companyId);
                phoneSmsRecordService.save(phoneSmsRecord);
                smsService.sendSmsMsg(IP, phone, newCode, companyId, companyAbbreviation,
                    companySignName); // 发送验证码

                // 返回数据
                result.setSuccess(true);
                result.setMessage("ok");
                result.setErrorcode("0");
                return result;
            }

            // 已经发送过验证码，判断发送间隔时长
            long time =
                (System.currentTimeMillis() - phoneSmsRecord.getExpired().getTime()) / 1000; // 获取已经发送了多上秒

            // 120秒内禁止发送
            if (time < 120) {
                result.setSuccess(false);
                result.setErrorcode("-4");
                result.setMessage("120秒内禁止发送");
                result.setLongValue(120 - time);
                return result;
            }

            // 120秒~1800秒发送旧的验证码
            if (time >= 120 && time < 30 * 60) {
                phoneSmsRecord.setExpired(new Date());
                phoneSmsRecord.setPhone(phone);
                phoneSmsRecordService.update(phoneSmsRecord);
                smsService.sendSmsMsg(IP, phone, phoneSmsRecord.getVcode(), companyId,
                    companyAbbreviation, companySignName);
            }

            // 超过1800秒发送新的验证码
            if (time >= 30 * 60) {
                String newCode = String.valueOf(RandomString.randomNum(4));
                phoneSmsRecord.setExpired(new Date());
                phoneSmsRecord.setVcode(newCode);
                phoneSmsRecord.setPhone(phone);
                phoneSmsRecordService.update(phoneSmsRecord);
                smsService.sendSmsMsg(IP, phone, newCode, companyId, companyAbbreviation,
                    companySignName);
            }

            // 返回数据
            result.setSuccess(true);
            result.setMessage("ok");
            result.setErrorcode("0");
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("系统异常");
            result.setErrorcode("-1");
        }
        return result;
    }

    /**
     * 验证短信验证码
     *
     * @param IP
     * @param phone 电话号
     * @param vcode 验证码
     * @return 返回码说明：<br> 1 ==> 发送成功<br> 0 ==> 还未发送验证码<br> -1 ==> 系统异常<br> -2 ==> 验证码已过期<br> -3 ==>
     * 验证码不正确<br> -4 ==> 参数错误<br>
     */
    @ResponseBody
    @RequestMapping("check")
    public Result<String> check(String IP, String phone, String vcode) {
        Result<String> result = new Result<String>(); // 返回对象
        try {
            // 参数验证
            if (null == phone || phone.isEmpty()) {
                result.setSuccess(false);
                result.setMessage("参数错误，请传入手机号");
                result.setErrorcode("-4");
                return result;
            }

            PhoneSmsRecord phoneSmsRecord = phoneSmsRecordService.findByPhone(phone);

            // 还没有发送验证码
            if (null == phoneSmsRecord) {
                result.setSuccess(false);
                result.setMessage("还未发送验证码");
                result.setErrorcode("0");
                return result;
            }

            Date date = new Date();
            long time = (date.getTime() - phoneSmsRecord.getExpired().getTime()) / 1000;

            // 过期，大于30分钟
            if (time > 30 * 60) {
                result.setSuccess(false);
                result.setMessage("验证码已过期");
                result.setErrorcode("-2");
                return result;
            }

            // 验证验证码
            if (StringUtils.equals(vcode, phoneSmsRecord.getVcode())) {
                phoneSmsRecordService.deleteByPhone(phone);
//				smsService.SmsSendBlackRecordCallBack(IP, phone); // 回滚数据库该手机的图片验证码机制
                result.setSuccess(true);
                result.setMessage("ok");
                result.setErrorcode("1");
            } else {
                // 验证码不正确时，将图片验证重置
                SmsSendBlackRecord record = blackRecordMapper.selectByPhoneAndIp(IP, phone);
                if (null != record) {
                    record.setValid(false);
                    record.setUpdated(date);
                    record.setLasted(date);
                    blackRecordMapper.updateByPrimaryKey(record);
                }
                result.setSuccess(false);
                result.setMessage("验证码不正确");
                result.setErrorcode("-3");
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("系统异常");
            result.setErrorcode("-1");
        }
        return result;
    }

    @RequestMapping(value = "query")
    public @ResponseBody
    String queryPhoneCode(String phone) {
        String vcode = "暂无";
        PhoneSmsRecord findByPhone = phoneSmsRecordService.findByPhone(phone);
        if (null != findByPhone) {
            vcode = findByPhone.getVcode();
        }
        return vcode;
    }

}
